﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DIProject.Stock
{
    public partial class ShiftsIn : Form
    {
        private ToolStripMenuItem menuItem = null;

        public ShiftsIn()
            : this(null)
        {
        }

        public ShiftsIn(ToolStripMenuItem menuItem)
        {
            InitializeComponent();

            this.menuItem = menuItem;
            if (menuItem != null)
                menuItem.Tag = this;
        }

        private void ShiftsIn_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (menuItem != null)
                menuItem.Tag = null;
        }
        //-------------------------------------------------------------------------------------------------
        private void ShiftsIn_Load(object sender, EventArgs e)
        {
            toolStripButtonUpdate.Enabled = false;
            toolStripButtonDelete.Enabled = false;
            toolStripRefresh_Click(toolStripButtonRefresh, EventArgs.Empty);
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void toolStripRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                shiftsInTableAdapter.Fill(stock.ShiftsIn);
            }
            catch (SqlException eq)
            {
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripInsert_Click(object sender, EventArgs e)
        {
            ShiftIn shiftIn = new ShiftIn(Util.ActionType.Insert, this);
            shiftIn.ShowDialog(this);
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripUpdate_Click(object sender, EventArgs e)
        {
            if (shiftsInGridView.CurrentCell != null)
            {
                ShiftIn shiftIn = new ShiftIn(Util.ActionType.Update, this);
                shiftIn.ShowDialog(this);
            }
        }
        //-------------------------------------------------------------------------------------------------
        private void toolStripDelete_Click(object sender, EventArgs e)
        {
            int n;
            if ((n = shiftsInGridView.SelectedRows.Count) > 0)
            {
                DIProject.DataSets.Stock.ShiftsInRow[] rowsToDelete = new DIProject.DataSets.Stock.ShiftsInRow[n];
                for (int i = 0; i < n; ++i)
                    rowsToDelete[i] = (DIProject.DataSets.Stock.ShiftsInRow)((DataRowView)shiftsInGridView.SelectedRows[i].DataBoundItem).Row;
                if (MessageBox.Show
                    (this
                    , string.Format
                        (n > 1
                        ? Properties.Resources.strDeleteShiftsIn
                        : Properties.Resources.strDeleteShiftIn
                        , n
                        , rowsToDelete[0].DocNumber
                        , rowsToDelete[0].DocDate
                        )
                    , Properties.Resources.strConfirmation
                    , MessageBoxButtons.YesNo
                    , MessageBoxIcon.Question
                    , MessageBoxDefaultButton.Button1
                    ) == DialogResult.Yes
                )
                {
                    try
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].Delete();
                        shiftsInTableAdapter.Update(stock.ShiftsIn);
                    }
                    catch (SqlException eq)
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].RejectChanges();
                        MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (Exception ex)
                    {
                        for (int i = 0; i < n; ++i)
                            rowsToDelete[i].RejectChanges();
                        MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private DIProject.DataSets.StockTableAdapters.ShiftInDownloadTableAdapter shiftInDownloadTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftInDownloadTableAdapter();
        private DIProject.DataSets.StockTableAdapters.ShiftInLinesDownloadTableAdapter shiftInLinesDownloadTableAdapter = new DIProject.DataSets.StockTableAdapters.ShiftInLinesDownloadTableAdapter();
        private void toolStripButtonDownload_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                decimal sum;
                int n, departmentId;
                DataTable document, docLines;
                DataRow documentOutRow, docOutLinesRow;
                DIProject.DataSets.Stock.ShiftsInRow shiftsInRow;
                DIProject.DataSets.Stock.ShiftInDownloadRow documentInRow;
                DIProject.DataSets.Stock.ShiftInLinesDownloadRow docInLinesRow;
                BinaryReader binaryReader = null;
                try
                {
                    binaryReader = new BinaryReader(File.OpenRead(openFileDialog.FileName));
                    departmentId = binaryReader.ReadInt32();
                    n = binaryReader.ReadInt32();
                    for (int i = 0; i < n; ++i)
                    {
                        document = DIProject.Util.DataTable.Load(null, binaryReader);
                        documentOutRow = document.Rows[0];
                        documentInRow = stock.ShiftInDownload.NewShiftInDownloadRow();
                        documentInRow.DocDate = DateTime.Today;
                        documentInRow.ContragentId = (int)documentOutRow[stock.ShiftOutUpload.DepartmentIdColumn.ColumnName];
                        documentInRow.ContragentDocDate = (DateTime)documentOutRow[stock.ShiftOutUpload.DocDateColumn.ColumnName];
                        documentInRow.ContragentDocNumber = (string)documentOutRow[stock.ShiftOutUpload.DocNumberColumn.ColumnName];
                        documentInRow.ParentId = (int)documentOutRow[stock.ShiftOutUpload.IdColumn.ColumnName];
                        documentInRow.MD = DateTime.Now;
                        documentInRow.MW = FirstForm.Login;
                        documentInRow.DocNumber = (string)documentOutRow[stock.ShiftOutUpload.DocNumberColumn.ColumnName];
                        stock.ShiftInDownload.AddShiftInDownloadRow(documentInRow);
                        shiftInDownloadTableAdapter.Update(documentInRow);

                        shiftsInRow = stock.ShiftsIn.NewShiftsInRow();
                        shiftsInRow.Id = documentInRow.Id;
                        shiftsInRow.DocDate = documentInRow.DocDate;
                        shiftsInRow.DocNumber = documentInRow.DocNumber;
                        shiftsInRow.DepartmentId = documentInRow.ContragentId;
                        shiftsInRow.DepartmentName = (string)documentOutRow[stock.ShiftOutUpload.DepartmentNameColumn.ColumnName];
                        shiftsInRow.ContragentDocDate = documentInRow.ContragentDocDate;
                        shiftsInRow.ContragentDocNumber = documentInRow.ContragentDocNumber;
                        shiftsInRow.MD = documentInRow.MD;
                        shiftsInRow.MW = documentInRow.MW;
                        shiftsInRow.DocNumber = documentInRow.DocNumber;
                        stock.ShiftsIn.AddShiftsInRow(shiftsInRow);
                        shiftsInRow.AcceptChanges();

                        sum = 0m;
                        docLines = DIProject.Util.DataTable.Load(null, binaryReader);
                        for (int j = 0, m = docLines.Rows.Count; j < m; ++j)
                        {
                            docOutLinesRow = docLines.Rows[j];
                            docInLinesRow = stock.ShiftInLinesDownload.NewShiftInLinesDownloadRow();

                            docInLinesRow.DocId = documentInRow.Id;
                            docInLinesRow.GoodsId = (int)docOutLinesRow[stock.ShiftOutLinesUpload.GoodsIdColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.BarCodeColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.BarCodeColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.DocQnttyColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.DocQnttyColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.QnttyColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.QnttyColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.SupplierGoodsIdColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.SupplierGoodsIdColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ManufacturerPriceColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ManufacturerPriceColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.SupplierPriceColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.SupplierPriceColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.SupplierSumNOTAXColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.SupplierSumNOTAXColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ImportMarkupColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ImportMarkupColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.SupplierMarkupColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.SupplierMarkupColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.BatchNumberColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.BatchNumberColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ReadyBeforeColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ReadyBeforeColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.MadeDateColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.MadeDateColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.NDSTaxColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.NDSTaxColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.NDSValueColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.NDSValueColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ReestrPriceColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ReestrPriceColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ReestrDateColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ReestrDateColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.GTDNumberColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.GTDNumberColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.CertificateNumberColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.CertificateNumberColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.CertificateDateColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.CertificateDateColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.CertificateOrgIdColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.CertificateOrgIdColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.RetailMarkupColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.RetailMarkupColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.RetailPriceColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.RetailPriceColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ContragentIdColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ContragentIdColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ContragentDocDateColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ContragentDocDateColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ContragentDocNumberColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.ContragentDocNumberColumn.ColumnName];
                            docInLinesRow[stock.ShiftInLinesDownload.ReturnLineIdColumn.ColumnName] = docOutLinesRow[stock.ShiftOutLinesUpload.LineIdColumn.ColumnName];
                            docInLinesRow.MD = DateTime.Now;
                            docInLinesRow.MW = FirstForm.Login;

                            stock.ShiftInLinesDownload.AddShiftInLinesDownloadRow(docInLinesRow);
                            shiftInLinesDownloadTableAdapter.Update(docInLinesRow);
                            sum += docInLinesRow.DocQntty * docInLinesRow.RetailPrice;
                        }
                        shiftsInRow.Lines = docLines.Rows.Count;
                        shiftsInRow.DocSum = sum;
                        shiftsInRow.AcceptChanges();
                    }
                }
                catch (SqlException eq)
                {
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (binaryReader != null)
                        binaryReader.Close();
                }
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (clickedCell != null)
            {
                updateToolStripMenuItem.Enabled = true;
                deleteToolStripMenuItem.Enabled = true;
            }
            else
            {
                updateToolStripMenuItem.Enabled = false;
                deleteToolStripMenuItem.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        private DataGridViewCell clickedCell = null;
        private void shiftsInGridView_MouseDown(object sender, MouseEventArgs e)
        {
            clickedCell = null;
            if (e.Button == MouseButtons.Right)
            {
                DataGridView.HitTestInfo hit = shiftsInGridView.HitTest(e.X, e.Y);
                if (hit.Type == DataGridViewHitTestType.Cell)
                    shiftsInGridView.CurrentCell = clickedCell = shiftsInGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void shiftsInGridView_CurrentCellChanged(object sender, EventArgs e)
        {
            if (shiftsInGridView.CurrentCell != null)
            {
                toolStripButtonUpdate.Enabled = true;
                toolStripButtonDelete.Enabled = true;
            }
            else
            {
                toolStripButtonUpdate.Enabled = false;
                toolStripButtonDelete.Enabled = false;
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
        private void shiftsInGridView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                e.Handled = true;
        }
        //-------------------------------------------------------------------------------------------------
        private void shiftsInGridView_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r' && shiftsInGridView.CurrentCell != null)
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
        }
        //-------------------------------------------------------------------------------------------------
        private void shiftsInGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            DataGridView.HitTestInfo hit = shiftsInGridView.HitTest(e.X, e.Y);
            if (hit.Type == DataGridViewHitTestType.Cell)
            {
                shiftsInGridView.CurrentCell = clickedCell = shiftsInGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
                toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
            }
        }
        //-------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------
    }
}